<template>
  <el-form :inline="true" :model="model" class="demo-form-inline">
    <el-form-item label="仓库编号">
      <el-input v-model="model.Warehouseid" placeholder="仓库编号" clearable />
    </el-form-item>
     <el-form-item label="仓库名称">
      <el-input v-model="model.Warehousename" placeholder="仓库名称" clearable />
    </el-form-item>
        <el-form-item>
      <el-button type="primary" @click="GetWareHouse">搜索</el-button>
      <el-button type="success" @click="open(100)"  >新增</el-button>
    </el-form-item>
  </el-form>


   <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="warehouseid" label="仓库编码" width="180"  />
    <el-table-column prop="warehousename" label="仓库名称" width="180" />
    <el-table-column prop="capacity" label="仓库容量" width="180" />
    <el-table-column prop="address" label="地址" width="180" />
        <el-table-column prop="librarylocationnum" label="库位数量" width="160" />
        <el-table-column prop="status" label="状态" width="140" >
      <template v-slot="scope">
        <el-tag v-if="scope.row.status == '0'" type="success">启用</el-tag>
        <el-tag v-else-if="scope.row.status == '1'" type="warning">停用</el-tag>
        <el-tag v-else-if="scope.row.status == '2'" type="danger">锁用</el-tag>
      </template>
        </el-table-column>
<el-table-column prop="creationTime" label="创建时间" width="160" >
      <template v-slot="scope">
        {{ new Date(scope.row.creationTime).toLocaleString() }}
      </template>
    </el-table-column>

        <el-table-column prop="" label="操作" width="180" >
            <template v-slot="scope">
                <el-button @click="del(scope.row.id)" type="danger">删除</el-button>
                <el-button @click="open(scope.row)" type="primary">修改</el-button>
            </template>
        </el-table-column>
  </el-table>

<!-- 分页导航 -->
<div class="pagination-container">
  <div class="pagination-info">
    当前第 <span class="highlight">{{ model.pageindex }}</span> 页 
    / 共 <span class="highlight">{{ model.totalpage }}</span> 页，
    本页 <span class="highlight">{{ tableData.length }}</span> 条数据
    / 共 <span class="highlight">{{ model.count }}</span> 条记录
  </div>
  
  <div class="pagination-actions">
    <el-button 
      size="small" 
      :disabled="model.pageindex === 1" 
      @click="goToFirstPage"
    >
      首页
    </el-button>
    <el-button 
      size="small" 
      :disabled="model.pageindex === 1" 
      @click="goToPrevPage"
    >
      上一页
    </el-button>

 <el-pagination
      background
      layout="pager"
      :total="model.count"
      :page-sizes="[2, 5, 10, 20, 50]"
      :page-size="model.pagesize"
      :current-page="model.pageindex"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      hide-on-single-page
    />
    
    <el-button 
      size="small" 
      :disabled="model.pageindex >= model.totalpage" 
      @click="goToNextPage"
    >
      下一页
    </el-button>
    <el-button 
      size="small" 
      :disabled="model.pageindex >= model.totalpage" 
      @click="goToLastPage"
    >
      尾页
    </el-button>
    
    <el-select v-model="model.pagesize" size="small" @change="handleSizeChange">
      <el-option v-for="size in [2, 5, 10, 20, 50]" :key="size" :label="`${size}条/页`" :value="size" />
    </el-select>
  </div>
</div>


   <el-dialog
    v-model="cnm.isopen"
    :title="cnm.title"
    width="1500px"
    top="5vh"
  >

  <div class="dialog-vertical-container">
    <!-- 基础信息部分 -->
    <el-card class="info-card">
      <div class="section-title">
        <h3>基础信息</h3>
      </div>
   <el-form
    ref="ruleFormRef"
    :model="WareHouse"
    :rules="rules"
        label-width="100px"
        class="warehouse-form"
  >


        <div class="form-row">
    <el-form-item label="仓库编号" prop="">
    <el-input v-model="WareHouse.Warehouseid" placeholder="系统自动生成" readonly disabled />
    </el-form-item>
    <el-form-item label="仓库名称" prop="Warehousename">
      <el-input v-model="WareHouse.Warehousename" placeholder="请输入仓库名称" />
    </el-form-item>
        </div>

        <div class="form-row">
        <el-form-item label="仓库容量" prop="Capacity">
      <el-input v-model="WareHouse.Capacity" placeholder="请输入仓库容量" />
    </el-form-item>
        <el-form-item label="仓库地址" prop="Address">
      <el-input v-model="WareHouse.Address" placeholder="请输入仓库地址" />
    </el-form-item>
        </div>

        <div class="form-row">
    <el-form-item label="部门" >
            <el-select v-model="WareHouse.Depid" placeholder="请选择部门" style="width: 100%">
              <el-option v-for="i in Librarylocation"  :label="i.depname" :value="i.depid" :key="i.depid" />
      </el-select>
    </el-form-item>
     <el-form-item label="库位数量" prop="librarylocationnum">
      <el-input v-model="WareHouse.librarylocationnum" placeholder="请输入库位数量" />
    </el-form-item>
     </div>
     <div>
          <el-form-item label="状态" >
            <el-radio-group v-model="WareHouse.Status" prop="Status" >
              <el-radio value="0">启用</el-radio>
              <el-radio value="1">停用</el-radio>
              <el-radio value="2">锁用</el-radio>
    </el-radio-group>
    </el-form-item>
     </div>

       

        <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
    </el-card>


    
    <!-- 库位信息部分 -->
    <el-card class="info-card">
      <div class="section-title">
        <h3>库位信息</h3>
      </div>


     <el-table :data="location" style="width: 100%" max-height="300" border class="location-table">
           <el-table-column type="selection" width="55" />

        <el-table-column label="序号" type="index" width="60" />
        
        <el-table-column prop="librarylocationid" label="库位编码" min-width="120" >
          <template v-slot="librarylocationid">
            <el-input v-model="librarylocationid.row.librarylocationid" placeholder="系统自动生成" readonly disabled  />
          </template>  
        </el-table-column>


        <el-table-column prop="librarylocationname" label="库位名称" min-width="120" >
         <template v-slot="librarylocationname">
             <el-input v-model="librarylocationname.row.librarylocationname" placeholder="请输入库位名称" />
         </template>
        </el-table-column>


        <el-table-column prop="empid" label="库位主管" min-width="120" >
          <template v-slot="empid">
            <el-input v-model="empid.row.empid" placeholder="请输入库位主管" /> 
          </template>
        </el-table-column>
       
        <el-table-column prop="memo" label="备注" min-width="150" >
          <template v-slot="memo">
            <el-input v-model="memo.row.memo" placeholder="请输入备注信息" />
          </template>
        </el-table-column>

          <el-table-column prop="status" label="状态" width="140" >
          <template v-slot="scope">
              <el-form-item label="状态" >
            <el-radio-group v-model="scope.row.Status" prop="Status" >
              <el-radio value="0">启用</el-radio>
              <el-radio value="1">停用</el-radio>
              <el-radio value="2">锁用</el-radio>
    </el-radio-group>
    </el-form-item>
          </template>
        </el-table-column>


    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button
          link
          type="primary"
          size="small"
          @click.prevent="deleteRow(scope.$index)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-button class="mt-4" style="width: 100%" @click="onAddItem">
    添加
  </el-button>

    </el-card>
  </div>
  </el-dialog>





</template>
<script setup lang="ts">
import axios from 'axios';
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { tr } from 'element-plus/es/locales.mjs';
import type { ComponentSize } from 'element-plus'
const dialogVisible = ref(false)

// 添加ID字段到WareHouse对象
const WareHouse=ref({
  Warehouseid: '',
  Warehousename: '',
  Capacity: '',
  Address: '',
  Depid:'',
  librarylocationnum: '',
  Status: ''
})
const model=reactive({
  pageindex:1,
  pagesize:5,
  Warehouseid:'',
  Warehousename:'',
  count:0,
  totalpage:0
})

const tableData = ref([{
  id:"",
 "warehouseid":'',
      "warehousename": "",
      "capacity": "",
      "address": "",
      "depid": '',
      "librarylocationnum": "",
      "status": '',
      "lastModificationTime": "",
      "lastModifierId": "",
      "creationTime": "",
      "creatorId": "",
}])

watch(model,()=>{
  GetWareHouse();
})

onMounted(()=>{
  // 获取仓库列表
GetWareHouse();
// 获取部门列表
GetLibrarylocation();




})

const GetWareHouse=()=>{
    axios.get("api/app/ware-houser/ware-houser-list",{
      params:{
        pageindex:model.pageindex,
        pagesize:model.pagesize,
        Warehouseid:model.Warehouseid,
        Warehousename:model.Warehousename
      }
    })
    .then(res=>{
        console.log("API返回数据:", res.data);
        
        if (res.data) {
            // 处理返回的数据结构
            if (res.data.pageData) {
                tableData.value = res.data.pageData;
            } else {
                tableData.value = res.data;
            }
            
            // 处理总数
            if (res.data.totalCount !== undefined) {
                model.count = res.data.totalCount;
            } else if (res.data.pageData && res.data.pageData.length > 0) {
                model.count = res.data.pageData.length;
            }
            
            // 处理总页数
            model.totalpage = res.data.totalPages || Math.ceil(model.count / model.pagesize);
            
            console.log("处理后的分页数据:", {
               tableData: tableData.value,
                count: model.count,
                totalPage: model.totalpage
            }); 
        }
    })
    .catch(error => {
        console.error("获取数据失败:", error);
     
    });
}
// 修改部门下拉框选项绑定
const Librarylocation=ref([{
  id: '',
  depid: '',
  depname: ''
}])

const GetLibrarylocation=()=>{
    axios.get("api/app/ware-houser/department-list")
    .then(res=>{

        if(res.data && res.data.data) {
            Librarylocation.value = res.data.data;
            console.log("处理后的部门数据:", Librarylocation.value);
        }
    })
    .catch(error => {
        console.error("获取部门列表失败:", error);
        ElMessage.error("获取部门列表失败");
    });
}

const handleSizeChange = (val: number) => {
  model.pagesize = val;
  model.pageindex = 1;
  GetWareHouse();
}

const handleCurrentChange = (val: number) => {
  model.pageindex = val;
  GetWareHouse();
}

// 添加分页导航方法
const goToFirstPage = () => {
  model.pageindex = 1;
  GetWareHouse();
}

const goToPrevPage = () => {
  if (model.pageindex > 1) {
    model.pageindex--;
    GetWareHouse();
  }
}

const goToNextPage = () => {
  if (model.pageindex < model.totalpage) {
    model.pageindex++;
    GetWareHouse();
  }
}

const goToLastPage = () => {
  model.pageindex = model.totalpage;
  GetWareHouse();
}

const ruleFormRef = ref<FormInstance>() 
const rules = reactive<FormRules>({
  Warehousename: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
  ],
  Capacity: [
    { required: true, message: '请输入仓库容量', trigger: 'blur' },
  ],
  Address: [
    { required: true, message: '请输入仓库地址', trigger: 'blur' },
  ],
  librarylocationnum: [
    { required: true, message: '请输入库位数量', trigger: 'blur' },
  ]
})

const cnm=reactive({
   title:"",
   isAdd:true,
   isopen:false
})


const codeView = async () => {
  try {
    const response = await axios.post(
      "api/app/dm_Encoderule/start-code",{},
      {
        params: {
          Formtypeid: "仓库信息"
        }
      }
    );

    if (response.data && response.data.code === 200) {
      WareHouse.value.Warehouseid = response.data.data;
      console.log("生成的仓库编码:", WareHouse.value.Warehouseid);
    } else {
      console.error("生成仓库编码失败:", response.data.message);
      ElMessage.error("生成仓库编码失败");
    }
  } catch (error) {
    console.error("请求失败:", error);
    ElMessage.error("请求失败，请检查网络连接");
  }
}


const UpdateWareHouse=ref({
  id:"",
  Warehouseid: '',
  Warehousename: '',
  Capacity: '',
  Address: '',
  Depid:'',
  Librarylocationnum: '',
  Status: ''
})
// 修改主表格中的修改按钮代码，传递整行数据而不仅仅是数字
// 修改open函数中的修改分支逻辑
const open=(row:any)=>{
  cnm.isopen=true;
  if(row==100)
  {
    // 新增逻辑保持不变
    WareHouse.value.Warehouseid="";
    WareHouse.value.Warehousename="";
    WareHouse.value.Capacity="";
    WareHouse.value.Address="";
    WareHouse.value.Depid="";
    WareHouse.value.librarylocationnum="";
    WareHouse.value.Status="";
    cnm.title="新增仓库";
    cnm.isAdd=true;
  }
  else{
    cnm.title="修改仓库"
    cnm.isAdd=false;
    if(typeof row === 'object' && row !== null) {
      // 赋值到 WareHouse.value，实现表单反填
      WareHouse.value.Warehouseid = row.warehouseid;
      WareHouse.value.Warehousename = row.warehousename;
      WareHouse.value.Capacity = row.capacity;
      WareHouse.value.Address = row.address;
      WareHouse.value.Depid = row.depid;
      WareHouse.value.librarylocationnum = row.librarylocationnum;
      WareHouse.value.Status = row.status !== null ? String(row.status) : '';
      // 只保留 id 到 UpdateWareHouse
      UpdateWareHouse.value.id = row.id;
    }
  }
}

const del=(id:any)=>{

   ElMessageBox.confirm(
    '亲 ！您确定真的要删除吗？？？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
       axios.delete("api/app/ware-houser/"+id+"/ware-houser",{
    params:{
      id:id
    }
  })
  .then(res=>{
      if(res.data.code==200)
      {
          ElMessage.success(res.data.message)
          GetWareHouse();
      }
      else
      {
          ElMessage.error(res.data.message)
      }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
}




 const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {


      if(cnm.isAdd == true){

        // 调用codeView方法生成仓库编号
       await codeView();
        
        console.log("111"+WareHouse.value.Warehouseid)
        if(WareHouse.value.Warehouseid!=""){
         axios.post("api/app/ware-houser/ware-houser", WareHouse.value)
        .then(res => {
            if(res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetWareHouse();
                
 
                cnm.isopen = false;
            } else {
                ElMessage.error(res.data.message)
            }
        })}
   
          await codeLibrarylocation();
  axios.post("api/app/location/location",[location.value])
  .then(res=>{
    if(res.data.code == 200) {

      ElMessage.success(res.data.message);
      getLocation();
    } else {
      ElMessage.error(res.data.message);
    }
  })

      } else {
        // 修改时，确保包含ID，避免循环引用
        const updateData = { ...WareHouse.value, id: UpdateWareHouse.value.id };
        axios.put("api/app/ware-houser/ware-houser", updateData)
        .then(res => {
            if(res.data.code == 200) {
                ElMessage.success(res.data.message)
                GetWareHouse();
                cnm.isopen = false;
            } else {
                ElMessage.error(res.data.message)
            }
        })
        console.log(updateData); // 打印提交的数据，确认ID是否正确包含
      } 

    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}



// 在位置添加库位编辑和删除的函数
const location=ref([
  {
    "librarylocationid": "",
      "librarylocationname": "",
      "warehouseid": "",
      "empid": "",
      "status": '',
      "memo": ""
}
])

const getLocation = () => { 
  axios.get("api/app/location/location-list",{
      params:{
        pageindex:model.pageindex,
        pagesize:model.pagesize
      }
    })
    .then(res=>{ 
        location.value=res.data.pageData;
    })
}

// 添加处理库位的函数
const editLocation = (row: any) => {
  // 编辑库位的逻辑
  console.log('编辑库位:', row);
  // 这里可以添加弹窗编辑库位的逻辑
  ElMessage.info('编辑库位功能开发中');
}

const deleteLocation = (id: string) => {
  // 删除库位的逻辑
  ElMessageBox.confirm(
    '确定要删除这个库位吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    // 调用删除API
    console.log('删除库位:', id);
    // 假设删除成功
    ElMessage.success('库位删除成功');
    // 重新加载数据
    getLocation();
  })
  .catch(() => {
    ElMessage.info('取消删除操作');
  });
}


import dayjs from 'dayjs'


const codeLibrarylocation = async () => {

    location.value.forEach(element => async () => {
     element.warehouseid= WareHouse.value.Warehouseid
      // 调用API生成库位编码
      element.librarylocationid = await axios.post(
        "api/app/dm_Encoderule/start-code",{},
        {
          params: {
            Formtypeid: "库位信息"
          }
        }
      );
      
      // 生成仓库ID
  element.warehouseid= await axios.post(
      "api/app/dm_Encoderule/start-code",{},
      {
        params: {
          Formtypeid: "库位信息"
        }
      }
    );
      
    });
  
}

const now = new Date()
const  Dm_Librarylocation=reactive({
  "librarylocationid": "",
      "librarylocationname": "",
      "warehouseid": "",
      "empid": "",
      "status": '',
      "memo": ""
})

const deleteRow = (index: number) => {
    location.value.splice(index, 1);}

const onAddItem = () => {
  now.setDate(now.getDate() + 1);
  location.value.push({
    librarylocationid: "",
    librarylocationname: "",
    warehouseid:'',
    empid: "",
    status: '0', // 默认启用状态
    memo: ""
  });
}


</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pagination-info {
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
  margin: 0 3px;
}

.pagination-actions {
  display: flex;
  align-items: center;
  gap: 5px;
}

.el-pagination {
  margin: 0 10px;
}

.el-table {
  margin-bottom: 20px;
}

.dialog-table {
  margin-top: 20px;
  overflow-x: auto;
}

.el-dialog {
  max-height: 90vh;
  overflow-y: auto;
}

.el-dialog__body {
  padding: 20px;
  overflow: auto;
}

/* 修改对话框内的布局结构，使用flex布局 */
.dialog-content {
  display: flex;
  flex-direction: row;
  gap: 20px;
  width: 100%;
}

.dialog-card {
  flex: 1;
  margin: 0;
}

.form-card {
  min-width: 45%;
}

.table-card {
  min-width: 45%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

@media (max-width: 768px) {
  .dialog-content {
    flex-direction: column;
  }
}

.dialog-flex-container {
  display: flex;
  gap: 20px;
  width: 100%;
}

.dialog-card {
  flex: 1;
  margin: 0;
  min-width: 0; /* 防止溢出 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

@media (max-width: 900px) {
  .dialog-flex-container {
    flex-direction: column;
  }
}

/* 添加CSS样式 */
.dialog-vertical-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
}

.info-card {
  width: 100%;
  margin-bottom: 10px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.section-title h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.operations {
  display: flex;
  gap: 5px;
}

.warehouse-form {
  margin-top: 15px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row .el-form-item {
  flex: 1;
}

.location-table {
  margin-top: 10px;
}
</style>